﻿using Communication.Channel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Windows.Forms;
using Channel = System.Threading.Channels.Channel;

namespace LEDVANCE.Oscilloscope.VirtualOscilloscope
{
    public class MessageChannel<T>
    {
        private CancellationTokenSource _cancellationTokenSource;
        private bool _isRunning = false;
        private Channel<T> _messageChannel; // 修改为 T 类型的 Channel
        private const int UI_UPDATE_INTERVAL = 100; // 100ms 更新一次

        public ISubject<T> DataReceivedSubject { get; }

        public MessageChannel(ISubject<T> _dataReceivedSubject)
        {
            InitializeChannel();
            MessageDisplayForm_Load(); // 注册窗体加载事件
            DataReceivedSubject = _dataReceivedSubject;
            // 窗体加载时开始接收消息
            _isRunning = true;
            StartReceivingMessages(); // 注意：这里不需要 await，因为这是一个事件处理程序
        }

        private void InitializeChannel()
        {
            // 初始化一个无界的 Channel
            _messageChannel = Channel.CreateUnbounded<T>();
        }

        private async Task StartReceivingMessages()
        {
            _cancellationTokenSource = new CancellationTokenSource();

            _ = Task.Run(async () =>
            {
                try
                {
                    while (!_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        // 从 Channel 中读取消息
                        var messageBytes = await _messageChannel.Reader.ReadAsync(_cancellationTokenSource.Token);
                        DataReceivedSubject.OnNext(messageBytes);

                    }
                }
                catch (TaskCanceledException)
                {
                    // 任务被取消，正常退出
                }
                catch (Exception ex)
                {

                }
            });
        }


        private void StopReceivingMessages()
        {
            _cancellationTokenSource?.Cancel();
        }


        // 窗体加载事件处理
        private void MessageDisplayForm_Load()
        {

        }

        // 窗体关闭事件处理
        private void MessageDisplayForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopReceivingMessages(); // 确保在窗体关闭时停止接收消息
        }

        // 在 AddMessageToChannelAsync 中添加更多的错误处理
        public async Task AddMessageToChannelAsync(T messageBytes)
        {
            try
            {
                await _messageChannel.Writer.WriteAsync(messageBytes);
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"无法写入消息到 Channel: {ex.Message}");
                // 可以在这里选择是否显示错误信息给用户
            }
        }
    }
}
